﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Deployment.Application;
using System.IO;

namespace Camping_Project.Forms
{
    public partial class FormValider : Form
    {
        private Camping_BDD bdd = new Camping_BDD();
        int ligne, id , IDEmail=0,IDEmploye=0;
        bool status;

        public FormValider(int IDEmploye)
        {
            InitializeComponent();
            this.IDEmploye = IDEmploye;
            status = false;
        }

        private void FormValider_Load(object sender, EventArgs e)
        {
            refreshDGVReserv();
        }

        private void dataGridViewReserv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            ligne = dataGridViewReserv.SelectedCells[0].RowIndex;
            id = (int)dataGridViewReserv["iDClientDataGridViewTextBoxColumn", ligne].Value;
            refreshDGVClient();
        }



        public void refreshDGVReserv()
        {
            //this.dataGridViewReserv.DataSource = from r in bdd.Reservation select c;



            var queryReserv = from reservation in bdd.Reservation
                              where reservation.Valide == false
                              select new
                              {
                                  reservation.IDReservation,
                                  reservation.DateDebut,
                                  reservation.DateFinApprox,
                                  reservation.DateFinDef,
                                  reservation.TypeEmp,
                                  reservation.NbAdultes,
                                  reservation.NbEnfants,
                                  reservation.NbAnimaux,
                                  reservation.NbVehicules,
                                  reservation.Electricite,
                                  reservation.PrixNuit,
                                  reservation.PrixAdulte,
                                  reservation.PrixEnfant,
                                  reservation.PrixAnimal,
                                  reservation.PrixElectricite,
                                  reservation.PrixVehicule,
                                  reservation.PrixTotal,
                                  reservation.PayementEffectue,
                                  reservation.IDClient,
                                  reservation.IDEmplacement,
                                  reservation.IDEmploye
                              };
           this.dataGridViewReserv.DataSource = queryReserv;

            dataGridViewReserv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

          }

        public void refreshDGVClient()
        {
            var queryCli = from client in bdd.Client
                                                 where client.IDClient == id
                                                 select new
                                                 {
                                                    client.IDClient,
                                                    client.Nom,
                                                    client.Prenom,
                                                    client.DateNaissance,
                                                    client.Adresse,
                                                    client.CodePostal,
                                                    client.Ville,
                                                    client.Pays,
                                                    client.Telephone,
                                                    client.Email
                                                 };
            this.dataGridViewClient.DataSource = queryCli;

            foreach (var c in queryCli)
            {
                IDEmail = c.IDClient;
            }

            dataGridViewReserv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        }

        private void dataGridViewClient_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            ligne = dataGridViewReserv.SelectedCells[0].RowIndex;
            status = true;
        }

        private void buttonValider_Click(object sender, EventArgs e)
        {
            DateTime dateLimite;
            
            if (status == true)
            {
                id = (int)dataGridViewReserv["iDReservationDataGridViewTextBoxColumn", ligne].Value;
                var reserv = (from r in bdd.Reservation
                              where r.IDReservation == id
                              select r).Single();
                reserv.Valide = true;
                reserv.IDEmploye = IDEmploye;

                if (reserv.PrixTotal == 0)
                {
                    dateLimite = (DateTime)reserv.DateFinApprox;
                }
                else
                {
                    dateLimite = (DateTime)reserv.DateFinDef;
                }

                //Affichage de la carte avec les emplacements dispo en fonction des parametres
                FormDispo fd = new FormDispo(reserv.TypeEmp, reserv.DateDebut, dateLimite);
                fd.ShowDialog();

                reserv.IDEmplacement = fd.getIdentfiant();

                //Sauvegarde des changements
                bdd.SaveChanges();
                refreshDGVReserv();
                getFormParent().getProgressBar().Value = 25;
                //dataGridViewClient.Rows.Clear();

                envoiEmail(reserv);

                getFormParent().getProgressBar().Value = 100;
                MessageBox.Show("La réservation a été validée", "Validation réussie", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                MessageBox.Show("Veuillez d'abord sélectionner un client !", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }


        public FormEmploye getFormParent()
        {
            FormEmploye parent = (FormEmploye)this.MdiParent;
            return parent;
        }

            
      

        private void envoiEmail(Reservation r)
        {
            //MessageBox.Show("" + IDEmail);
            string body,begin,last,all,totalInfo,totalInfo2,elect;
            var cli = (from c in bdd.Client
                       where c.IDClient == IDEmail
                       select c).Single();

            getFormParent().getProgressBar().Value = 40;

            string typeEmpl;

            if(r.TypeEmp == true)
            {
                typeEmpl = "tente";
            }
            else
            {
                typeEmpl = "caravane";
            }

            if (r.Electricite == true)
            {
                elect = "Oui";
            }
            else
            {
                elect = "Non";
            }

            begin = System.IO.File.ReadAllText(Path.GetDirectoryName(Application.ExecutablePath)+@"\mailFirst.txt");
            //MessageBox.Show(Path.GetDirectoryName(Application.ExecutablePath)+ "/mailFirst.txt");
            //MessageBox.Show(begin);
            last = System.IO.File.ReadAllText(Path.GetDirectoryName(Application.ExecutablePath)+@"\mailLast.txt");
            //MessageBox.Show(last);



            body = "Bonjour Monsieur/Madame " + cli.Nom.Trim() + " " + cli.Prenom.Trim() + " , <br/>"
            + "votre réservation a bien été validée par notre staff pour les dates suivantes <br/>"
            + "Date d'arrivée : " + String.Format("{0:d/M/yyyy}",r.DateDebut) + " , ";

            if (r.PrixTotal == 0)
            {
                body += "Date approximative de départ : " + String.Format("{0:d/M/yyyy}", r.DateFinApprox) + "<br/>";
                totalInfo = "Non calculée (*)";
                totalInfo2 = "(*)Le total ne peut etre calculé que lorsque la date définitive de départ a été définie<br/>";
            }
            else
            {
                body += "Date de départ définitive : " + String.Format("{0:d/M/yyyy}", r.DateFinDef) + "<br/>";
                totalInfo = ""+r.PrixTotal;
                totalInfo2 = "<br/>";
            }

            //Details de la réservation
            body += @"<br/><table cellspacing=2 cellpadding=1 border=1>
		<tr>
				<th>Details</th>
				<th>Infos</th>		
		
		</tr>
		
		<tr>
				<td>Nombre d'adultes</td>
				<td>" +r.NbAdultes+@"</td>
	    </tr>
		
		<tr>
				<td>Nombre d'enfants</td>
				<td>"+r.NbEnfants+@"</td>
	    </tr>
		
		<tr>
				<td>Nombre d'animaux</td>
				<td>" + r.NbAnimaux + @"</td>
	    </tr>
		
	    <tr>
				<td>Nombre de véhicules</td>
				<td>" + r.NbVehicules + @"</td>
	    </tr>
		
		<tr>
				<td>Type d'emplacement</td>
				<td>" + typeEmpl + @"</td>
	    </tr>

		<tr>
				<td>Electricité ?</td>
				<td>" + elect + @"</td>
	    </tr>	

		<tr>
				<td>Prix total</td>
				<td>" + totalInfo + @"</td>
	    </tr>	

        </table></br>";

            body += totalInfo2;


            body += "</br>Votre numero d'emplacement pour votre " + typeEmpl + " est le <b>" + r.IDEmplacement + "</b>.<br/><br/> La carte du camping se trouve sur notre site web. </br>";

            body += "Merci de votre confiance et a tres bientot. </br>Vous pouvez consulter les détails de votre réservation en vous connectant sur votre compte sur notre site internet";


            all = begin + body + last;
            //MessageBox.Show(all);

            try
            {
                getFormParent().getProgressBar().Value = 50;
                System.Net.NetworkCredential _Credential = new System.Net.NetworkCredential("mailsender7100@gmail.com" ,"azerty123456" );
                System.Net.Mail.MailMessage _MailMessage = new MailMessage();
                _MailMessage.To.Add(cli.Email.Trim());
                _MailMessage.Subject = "Validation de votre réservation";
                _MailMessage.IsBodyHtml = true;
                _MailMessage.From = new System.Net.Mail.MailAddress("mailsender7100@gmail.com","Camping Soleil");
                _MailMessage.Body = all;

                System.Net.Mail.SmtpClient _SmtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com");
                _SmtpClient.UseDefaultCredentials = false;
                _SmtpClient.EnableSsl = true;
                _SmtpClient.Credentials = _Credential;
                _SmtpClient.Port = 587;
                _SmtpClient.Send(_MailMessage);
                getFormParent().getProgressBar().Value = 75;
            MessageBox.Show("Un email de validation a été envoyé a l'adresse "+cli.Email.Trim(),"Email envoyé",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Gmail Sender");
            }

        }

        

    }
}
